import { Component, OnInit, Input, ViewChild } from '@angular/core';
import { NavParams, ModalController, NavController, LoadingController } from '@ionic/angular';
import * as $ from 'jquery';
import { ToolService } from 'src/app/service/tool.service';
import { PopwinService } from 'src/app/service/popwin.service';
import { UrlService } from 'src/app/service/url.service';
import { HttpService } from 'src/app/service/http.service';
import { ConfigService } from 'src/app/service/config.service';
import { Router } from '@angular/router';
import { Storage } from '@ionic/storage';

@Component({
  selector: 'app-bet',
  templateUrl: './bet.component.html',
  styleUrls: ['./bet.component.scss'],
})
export class BetComponent implements OnInit {
  public isEdit: boolean = false;
  public showFastWin: boolean = false;//是否显示快速选择的窗口
  public showNumWin: boolean = false;//是否显示需要填写的数据
  public showData: any[];//选择倍率存放的数组
  public betNum: any;//选择下载倍率的数量
  public betTotalMoney: any;//选择倍率的所有的金额
  private tempTotalMoeny: any;//倍率金额的中间值
  public presetArr: any[];//预设置金额
  private presetPrice: any = 0;//批量的预选框里面的值
  private paramData: any;
  private playCode: any;//玩法的code码
  private code: any;//彩种的code
  private lotName: any;//玩法名字
  private lotteryId: any;//lotid
  private isOpen;//是否开启(1开,0关)
  public selectNum;//可选金额的个数

  constructor(private navParams: NavParams, private modalCtrl: ModalController, private popWin: PopwinService, private http: HttpService, private navCtrl: NavController, private loadingCtrl: LoadingController, private router: Router, private store: Storage) {
    this.paramData = this.navParams.data;
    this.showData = this.paramData.value;
    this.betNum = this.showData.length;
    this.betTotalMoney = 0;
    this.tempTotalMoeny = 0;
    this.playCode = this.paramData.playCode;
    this.code = this.paramData.code;
    this.lotName = this.paramData.name;
    this.lotteryId = this.paramData.lotteryId;
    console.log(this.showData);
  }

  ngOnInit() { }
  /**
   * 关闭modal
   */
  closeModal(isUpdate = false) {
    this.paramData.modal.dismiss({
      'result': isUpdate
    });
  }
  /**
   * 点击编辑
   */
  onEdit() {
    this.isEdit = !this.isEdit;
  }
  /**
   * 预设金额
   */
  onSetMoney(mark) {
    if (mark == "one") {//预设
      this.showFastWin = true;
      this.showNumWin = true;
    }
    this.store.get("key").then((data) => {
      let tempData = data;
      let jsonData = ToolService.isStringJSON(tempData) ? JSON.parse(tempData) : '';
      if (ToolService.isEmpty(jsonData)) {
        //为空的一个判断
        if (mark == "two") {
          this.popWin.toast("没有设置预设金额");
          return;
        }
        this.isOpen = 1;//没有默认开启
      } else {
        if (jsonData.isSet == 0) {
          //判断的处理
          if (mark == "two") {
            this.popWin.toast("已经禁止了预设置金额");
            return;
          }
          this.isOpen = 0;//原先的关闭状态
          this.presetArr = jsonData.data.split(',');
        } else if (jsonData.isSet == 1) {
          this.isOpen = 1;//原先的开启状态
          this.showFastWin = true;
          if (ToolService.isEmpty(jsonData.data)) {
            this.presetArr = [];
          } else {
            this.presetArr = jsonData.data.split(',');
          }
          if (mark == "two" && this.presetArr.length == 0) {
            this.popWin.toast("还没有预设金额");
            this.showFastWin = false;
            return;
          }
          console.log("wefwefewf");
          if (mark == "two" && this.presetArr.length > 0) {//显示预选金额的页面
            this.showNumWin = false;
            this.selectNum = this.presetArr.length;
          }
        }
      }
    });
  }
  /**
   * 选中预设置金额
   */
  onSelectpresetVal(index, value) {
    $(".select-win-res span").removeClass("select-win-res-active");
    $(".select-win-res span").eq(index).addClass("select-win-res-active");
    this.presetPrice = value;
    //m-contain-select-d-active
  }
  /**
   * 关闭快速选择
   */
  onCloseFast(status) {
    this.isOpen = status;
  }
  /**
   * 开启快速选择
   */
  onOpenFast(status) {
    this.isOpen = status;
  }
  /**
   * 缓存预设置的数据
   */
  setPresetData(status) {
    let tempArr: any[] = [];
    $(".preset_input").each(function (index) {
      let tempVal = $(this).val();
      if (ToolService.isNumber(tempVal) && !ToolService.isEmpty(tempVal)) {
        tempArr.push($(this).val());
      }
    });
    let data = '{"data":"' + tempArr + '","isSet":"' + status + '"}';
    this.store.set("key", data);
    console.log(JSON.parse(data));
  }

  /**
   * 关闭快速选择的页面
   */
  onSubmitFast(mark) {
    this.showFastWin = false;
    if (mark == "one") {
      this.setPresetData(this.isOpen);
    } else if (mark == "two") {
      if (!ToolService.isEmpty(this.presetPrice)) {
        $("#inputCach").val(this.presetPrice);
        this.onAllCachChange();
      }
    }
  }
  /**
   * 下注的按钮
   */
  async onBet() {
    let that = this;
    let obj = "{\"lotcode\":\"" + that.playCode + "\",\"rows\":" + JSON.stringify(that.showData) + "}";
    console.log("下注的参数:", obj);
    const loading = await this.loadingCtrl.create({ message: "提交中...", duration: 10000, mode: 'ios' });
    await loading.present();
    this.popWin.loading("", "bubbles", 1000);

    let token = $("app-root").attr("token");
    let sessid = $("app-root").attr("sessid");
    let uid = $("app-root").attr("uid");
    let encrypt = (!ToolService.isEmpty($("app-root").attr("encrypt")) && $("app-root").attr("encrypt")=='1') ? 1 : 0;
    let baseParam;
    if (ToolService.isEmpty(sessid)) {
      baseParam = { "token": ToolService.isEmpty(token) ? "" : token, "data": ToolService.aesEncode(obj), "tross": "createorder" , "encrypt": encrypt, "uid": uid,"v":ConfigService.APP_VERSION};  
    } else {
      baseParam = { "token": ToolService.isEmpty(token) ? "" : token, "sessid": sessid, "data": ToolService.aesEncode(obj), "tross": "createorder", "encrypt": encrypt , "uid": uid,"v":ConfigService.APP_VERSION};  
    }
    var api = ConfigService.SERVER_PATH + UrlService.LOTTERY_CREATEORDER;
    $.ajax({
      url: api, data: baseParam, dataType: 'json', success: function (res) {
        let data = res
        loading.dismiss();
        if (data.code == ConfigService.SUCCESS_CODE) {
          //成功的逻辑
          let tempData = ToolService.aesDecodeToJson(data.data);
          that.closeModal();
          //   that.popWin.toast(data.message);
          let param = "{\"res\":\"" + JSON.stringify(tempData) + "\",\"playCode\":\"" + that.code + "\",\"lotName\":\"" + that.lotName + "\",\"lotteryId\":\"" + that.lotteryId + "\"}";
          that.router.navigate(['/betsuccess'], {
            queryParams: { "p": ToolService.paramAESEncrypt(param)}
          });
        } else if (data.code == ConfigService.FAIL_CODE) {
          that.popWin.toast(data.message);
        } else if (data.code == ConfigService.LOGIN_CODE) {
          that.navCtrl.navigateForward("/login");
        } else if (data.code == ConfigService.BET_CHANGE_RATE) {
          that.closeModal(true);
          that.popWin.toast(data.message);
        } else {
          that.popWin.toast(data.message);
        }
      }, complete: function () {
        loading.dismiss();
      }, type: 'POST'
    });
  }
  /**
   * 删除选择的倍率
   */
  onDeleteLot(index) {
    this.showData.splice(index, 1);
    this.betNum = this.showData.length;
    let data = this.showData;
    this.betTotalMoney = 0;
    for (let i = 0; i < data.length; i++) {
      this.betTotalMoney += parseInt(data[i]['cash'])
    }
  }
  /**
   * 每个单独的倍率的输入数据
   */
  onSigleCashChange(index) {
    let inputVal = $("#cach_" + index).val() + ""
    let tempVal = ToolService.isNumber(parseInt(inputVal)) ? parseInt(inputVal) : 0;
    this.showData[index]['cash'] = tempVal;
    this.betTotalMoney = this.tempTotalMoeny + tempVal;
  }
  /**
   * 单独触发倍率的输入数据
   */
  onSigleCashFocus(index) {
    this.tempTotalMoeny = 0;
    let data = this.showData;
    for (let i = 0; i < data.length; i++) {
      if (i != index) {
        this.tempTotalMoeny += parseInt(data[i]['cash']);
      }
    }
  }
  /**
   * 批量处理金额的问题
   */
  onAllCachChange() {
    let tempVal = $("#inputCach").val() + "";
    let num = ToolService.isNumber(parseInt(tempVal)) ? parseInt(tempVal) : 0;;
    let data = this.showData;
    for (let i = 0; i < data.length; i++) {
      data[i]['cash'] = num;
    }
    this.betTotalMoney = data.length * num;
  }
}
